#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <signal.h>

#define N 32
#define M 256

enum{
    L=0x1,  //登录
    C,  //聊天
};


typedef struct{
    int type;//消息类型
    char name[N];
    char text[M];//消息正文
}MSG;

#define LEN sizeof(MSG)

int main(int argc, const char *argv[])
{
    int sockfd;
    struct sockaddr_in serveraddr;
    MSG msg;
    pid_t pid;
    socklen_t len=sizeof(struct sockaddr);
	char buf[M] = "";
    
    if(argc!=3){
        printf("user:%s ip port",argv[0]);
        return -1;
    }

    //创建socket
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd < 0){
        perror("socket err");
        exit(-1);
    }

    //指定服务器地址
    bzero(&serveraddr,len);
    serveraddr.sin_family = AF_INET;
    serveraddr.sin_port = htons(atoi(argv[2]));
    serveraddr.sin_addr.s_addr = inet_addr(argv[1]);

    //输入用户名，并发给服务器登录信息
    puts("====================client login=================");
	puts("请输入用户名:");
	scanf("%s",msg.name);
	getchar();
	msg.type = L;
	sendto(sockfd, &msg,LEN,0,(struct sockaddr *)&serveraddr, len);

    //fork--子进程发送，父进程接收
	pid = fork();
	if(pid < 0)
	{
		printf("fail to fork\n");
		return -1;
	}
	else if(pid > 0)
	{
		while(1)
		{
			recvfrom(sockfd, buf, M, 0,(struct sockaddr *)&serveraddr, &len);
			printf("%s\n",buf);
			memset(buf,0,M);
		}
	}
	else
	{
//		while(1)
		{
			scanf("%s",msg.text);
			getchar();
			msg.type = C;
			sendto(sockfd, &msg, LEN, 0,(struct sockaddr *)&serveraddr, len);
		}
	}
}
